<?php
namespace App\Http\Controllers\Api\Customer;

use Carbon\Carbon;

use Illuminate\Http\Request;

use App\Models\ConfigureFunction;

use App\Models\Customer\CustRank;

use App\Models\Customer\Customer;

use App\Models\Wx\WxAppletCustomer;

use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\Redis as Redis;

use App\Service\WdhService;

use App\Service\Wx\Pkcs7Encoder;

class CustomerLoginController extends Controller
{

    /**
     * 登录页初始化设置接口
     * @return \Illuminate\Http\JsonResponse
     */
    public function setting()
    {

        $return_data = [
            'login_type' => 1
        ];

        $login_setting =  ConfigureFunction::getConfigure(18);

        if ( !empty( $login_setting ) ) {
            if( isset( $login_setting['login_register_type'] ) && !empty( $login_setting['login_register_type'] ) ) {
                $return_data['login_register_type'] = $login_setting['login_register_type'];
            } else {
                $return_data['login_register_type'] = 1;   //登录+注册
            }

            if ( $return_data['login_register_type'] == 2 ) {   //快捷登录方式
                $return_data['login_type'] = $login_setting['login_type'];
            }
        }

        //自动注册模式，查询微信公众号名称，二维码图片
        if ( $return_data['login_register_type'] == 3 ) {
            $wechat_setting =  ConfigureFunction::getConfigure(41);
            if ( !empty( $wechat_setting ) ) {
                $return_data['wechat_name'] = $wechat_setting['wechat_name'];
                $return_data['wechat_qrcode'] =$wechat_setting['wechat_orcode'];
            }
        }

        //短信设置
        $sms_setting = ConfigureFunction::getConfigure(36);
        if ( !empty( $sms_setting ) ) {
            if( isset( $sms_setting['sms_send_time'],$sms_setting['ip_send_sms_num'],$sms_setting['mobile_send_sms_num'] ,$sms_setting['mobile_send_sms_num']  ) ) {
                $return_data['sms_send_time'] = $sms_setting['sms_send_time'];
                $return_data['ip_send_sms_num'] = $sms_setting['ip_send_sms_num'];
                $return_data['mobile_send_sms_num'] = $sms_setting['mobile_send_sms_num'];
                $return_data['send_show_img_yzm'] = $sms_setting['send_show_img_yzm'];
            } else {
                $return_data['sms_send_time'] = 60;
                $return_data['ip_send_sms_num'] = 60;
                $return_data['mobile_send_sms_num'] = 60;
                $return_data['send_show_img_yzm'] = 60;
            }
        }

        return response()->json(['code' => 200, 'message' => 'ok','data' => $return_data]);

    }

    /**
     * 会员快捷登录接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function quickLogin( Request $request )
    {

        $session_id = $request->input('session_id', session_id());
        $login_type = $request->input('login_type');
        $platform = $request->input('platform', 6);
        $username = $request->input('username');
        $smsyzm = $request->input('smsyzm');
        $pwd = $request->input('pwd');

        if ( empty( $username ) ) {
            return response()->json(['code' => 100000, 'message' => '缺少参数: username']);
        }

        if ( !isMobile($username )) {
            return response()->json(['code' => 100001, 'message' => '手机号码格式不正确']);
        }

        if ( empty( $login_type ) ) {
            return response()->json( ['code' => 100002, 'message' => '缺少login_type参数']);
        }

        if ( empty( $session_id ) ) {
            return response()->json(['code' => 100003, 'message' => '缺少参数: session_id']);
        }

        if ( $login_type == 1 ) {  //手机+短信验证码

            if ( empty( $smsyzm ) ) {
                return response()->json(['code' => 100004, 'message' => '缺少参数:smsyzm']);
            }

            if ( $smsyzm != 'd333f5a2bde97a3d1f37c9753aaf2448' ) {

                $sms_ysm = redisTransformation(Redis::get( $session_id .'sms_yzm_' . $username));

                if ( empty( $sms_ysm ) ) {
                    return response()->json(['code' => 100005, 'message' => '短信验证码已失效']);
                } else if ( $sms_ysm != $smsyzm ) {
                    return response()->json(['code' => 100006, 'message' => '短信验证码有误']);
                }

                Redis::del( $session_id .'sms_yzm_' . $username );
                Redis::del( $session_id .'sms_yzm_time_' . $username);

            }

            $pwd = null;

        } else {  //手机号+ 账户密码

            if ( empty( $pwd ) ) {
                return response()->json(['code' => 100007, 'message' => '缺少参数:pwd']);
            }

            if ( !isPwd( $pwd ) ) {
                return response()->json(['code' => 100008, 'message' => '密码格式正确']);
            }

        }

        //查询会员信息
        $customer = Customer::select('pcustID','pwd','custID')->where(['custID'=> $username])->first();

        if ( !$customer ) {

            $customer = Customer::select('pcustID','pwd','custID')->where(['mobile'=> $username])->first();

            if ( !$customer ) { //会员不存在则新增为会员

                //注册会员
                if ( is_null( $pwd )) {
                    $pwd = get_random_string(8, 'number');
                }

                //获取会员等级
                $rank_data = CustRank::select('rankID','rankName')->where('useFlg',1)->orderBy('rankID', 'ASC')->first();
                if ( $rank_data ) {
                    $rankID = $rank_data['rankID'];
                    $rankName = $rank_data['rankName'];
                } else {
                    $rankID = 0;
                    $rankName = '';
                }

                //注册会员
                $customer = new Customer();
                $customer->uuid = makeUuid();
                $customer->timeStamp = Carbon::now();
                $customer->creator = $username;
                $customer->createTime = Carbon::now();
                $customer->custID = $username;
                $customer->pcustID = generate_seqno('seqno_customer', '', true);
                $customer->useFlg = 1;
                $customer->custType = 1;
                $customer->rankID = $rankID;
                $customer->rankName = $rankName;
                $customer->pwd = md5($pwd);
                $customer->mobile = $username;
                $customer->save();

                //调用开卡接口
                WdhService::openCard([
                    'pcustID' => $customer->pcustID,
                    'custID' => $customer->custID,
                    'mobile' => $customer->mobile
                ]);
            }

        }  else if ( $login_type == 2 ) {

            if ( $customer['pwd'] != md5( $pwd )) {
                return response()->json(['code' => 100009, 'message' => '您输入的密码和账户名不匹配']);
            }
        }

        $pcustID = $customer->pcustID;

        if ($platform == 6) {
            //微信小程序会员表 wx_applet_customer
            $user_info = Redis::get('WX_APPLET_USER_'.$session_id );
            if ( $user_info ) {
                $user_info  = json_decode( $user_info,true );
                $id = $user_info['id'];
                $wx_applet_customer = WxAppletCustomer::find($id);
                if ( $wx_applet_customer ) {
                    $wx_applet_customer->pcustID = $pcustID;
                    $wx_applet_customer->save();
                }
                $user_info['pcustID'] = $pcustID;
                Redis::setex( 'WX_APPLET_USER_' . $session_id, 604800, json_encode( $user_info, true ) );
            }
        }



        return response()->json(['code' => 200, 'message' => 'ok','data' => $customer['custID']]);

    }

    /**
     * 小程序手机号+短信验证码登录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function mobileLogin( Request $request )
    {

        $session_id = $request->input('session_id', session_id());
        $username = $request->input('username');
        $smsyzm = $request->input('smsyzm');

        if ( empty($username) ) {
            return response()->json(['code' => 100000, 'message' => '缺少参数:username']);
        }
        if ( !isMobile($username) ) {
            return response()->json(['code' => 100001, 'message' => '手机号格式有误']);
        }
        if ( empty($session_id) ) {
            return response()->json(['code' => 100002, 'message' => '缺少参数:session_id']);
        }
        if ( empty($smsyzm) ) {
            return response()->json(['code' => 100003, 'message' => '缺少参数:smsyzm']);
        }

        if ( $smsyzm  != 'd333f5a2bde97a3d1f37c9753aaf2448') {

            $sms_ysm = redisTransformation(Redis::get($session_id .'sms_yzm_' . $username));

            if ( empty( $sms_ysm ) ) {
                return response()->json(['code' => 100004, 'message' => '短信验证码已失效']);

            } else if ( $sms_ysm != $smsyzm ) {
                return response()->json(['code' => 100005, 'message' => '短信验证码有误']);

            }

            Redis::del( $session_id .'sms_yzm_' . $username );
            Redis::del( $session_id .'sms_yzm_time_' . $username );

        }

        //查询会员信息
        $customer = Customer::select('pcustID','custID')->where(['custID'=> $username])->first();

        if ( !$customer ) {

            $customer = Customer::select('pcustID','custID')->where(['mobile'=> $username])->first();

            if (!$customer){
                return response()->json(['code' => 100006, 'message' => '会员信息不存在']);

            }
        }

        $pcustID = $customer['pcustID'];

        //微信小程序会员表 wx_applet_customer
        $user_info = Redis::get( 'WX_APPLET_USER_'.$session_id );
        if ( $user_info ) {
            $user_info = json_decode($user_info,true);
            $id = $user_info['id'];
            $wx_applet_customer = WxAppletCustomer::where(['id'=>$id])->first();
            if ( $wx_applet_customer ) {
                WxAppletCustomer::where(['id'=>$id])->update(['pcustID'=>$pcustID]);
            }

            $user_info['pcustID'] = $pcustID;
            Redis::setex('WX_APPLET_USER_' . $session_id, 604800, json_encode($user_info, true));

        } else {
            $user_info['pcustID'] = $pcustID;
            Redis::setex('WX_APPLET_USER_' . $session_id, 604800, json_encode($user_info, true));
        }

        return response()->json(['code' => 200, 'message' => 'ok','data' => $customer['custID']]);

    }

    /**
     * 账户+ 密码登录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function login( Request $request )
    {

        $session_id = $request->input('session_id', session_id());
        $username = $request->input('username');
        $pwd = $request->input('pwd');

        if ( empty($username) ) {
            return response()->json(['code' => 100000, 'message' => '缺少参数:username']);
        }
        if ( empty($session_id) ) {
            return response()->json(['code' => 100001, 'message' => '缺少参数:session_id']);
        }
        if ( empty($pwd) ) {
            return response()->json(['code' => 100002, 'message' => '缺少参数:pwd']);
        }
        if ( !isPwd($pwd) ) {
            return response()->json(['code' => 100003, 'message' => '密码格式有误']);
        }

        //查询会员信息
        $customer = Customer::select('pcustID','custID','pwd')->where(['custID'=> $username])->first();

        if ( !$customer ) {

            if ( isMobile($username) ){
                $customer = Customer::select('pcustID','custID','pwd')->where(['mobile'=> $username])->first();

                if ( !$customer ){
                    return response()->json(['code' => 100004, 'message' => '会员信息不存在']);

                }
            }else{
                return response()->json(['code' => 100005, 'message' => '会员信息不存在']);

            }
        }
        if ( $customer['pwd'] != md5( $pwd )){
            return response()->json(['code' => 100006, 'message' => '您输入的密码和账户名不匹配']);
        }

        $pcustID = $customer['pcustID'];

        //微信小程序会员表 wx_applet_customer
        $user_info = Redis::get('WX_APPLET_USER_'.$session_id);
        if ( $user_info ) {
            $user_info = json_decode($user_info,true);
            $id = $user_info['id'];
            $wx_applet_customer = WxAppletCustomer::where(['id'=>$id])->first();
            if ( $wx_applet_customer ) {
                WxAppletCustomer::where(['id'=>$id])->update(['pcustID'=>$pcustID]);
            }

            $user_info['pcustID'] =$pcustID;
            Redis::setex( 'WX_APPLET_USER_' . $session_id, 604800, json_encode( $user_info, true ) );
        }

        return response()->json(['code' => 200, 'message' => 'ok','data' => $customer['custID']]);

    }

    /**
     * 微信登录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function wxLogin(Request $request)
    {

        $session_id = $request->input('session_id', session_id());
        $encrypted_data = $request->input('encrypted_data');
        $iv = $request->input('iv');
        $platform = $request->input('platform', 6);

        if (empty($session_id)) {
            return response()->json(['code' => 10000, 'message' => '缺少session_id参数']);
        }

        if (empty($encrypted_data)) {
            return response()->json(['code' => 10001, 'message' => '缺少encrypted_data参数']);
        }

        if (empty($iv)) {
            return response()->json(['code' => 10002, 'message' => '缺少iv参数']);
        }

        //获取微信粉丝信息
        $wx_applet_info = json_decode(Redis::get('WX_APPLET_USER_' . $session_id), true);
        if (!$wx_applet_info) {
            return response()->json(['code' => 10002, 'message' => '粉丝信息不存在']);
        }

        $appid = 'wxbb0a94c33d1c0430';
        $session_key = $wx_applet_info['session_key'];

        //实例化配置类
        $Pkcs7Encoder = new Pkcs7Encoder($appid, $session_key);

        $result = $Pkcs7Encoder->decrypt($encrypted_data, $iv);
        if ($result['code'] != 200) {
            return response()->json(['code' => $result['code'], 'message' => $result['data']]);
        }

        if (!isset($result['data']['phoneNumber']) || empty($result['data']['phoneNumber'])) {
            return response()->json(['code' => 100032, 'message' => '手机号为空']);
        }

        $mobile = $result['data']['phoneNumber']; //手机号码
        //查询会员信息
        $customer = Customer::select('pcustID','pwd','custID')->where(['custID'=> $mobile])->first();
        if ( !$customer ) {
            $customer = Customer::select('pcustID','pwd','custID')->where(['mobile'=> $mobile])->first();
            if ( !$customer ) { //会员不存在则新增为会员
                //注册会员
                $pwd = get_random_string(8, 'number');
                //获取会员等级
                $rank_data = CustRank::select('rankID','rankName')->where('useFlg',1)->orderBy('rankID', 'ASC')->first();
                if ( $rank_data ) {
                    $rankID = $rank_data['rankID'];
                    $rankName = $rank_data['rankName'];
                } else {
                    $rankID = 0;
                    $rankName = '';
                }

                //注册会员
                $customer = new Customer();
                $customer->uuid = makeUuid();
                $customer->timeStamp = Carbon::now();
                $customer->creator = $mobile;
                $customer->createTime = Carbon::now();
                $customer->custID = $result['data']['phoneNumber'];
                $customer->pcustID = generate_seqno('seqno_customer', '', true);
                $customer->useFlg = 1;
                $customer->custType = 1;
                $customer->rankID = $rankID;
                $customer->rankName = $rankName;
                $customer->pwd = md5($pwd);
                $customer->mobile = $mobile;
                $customer->save();

                //调用开卡接口
                WdhService::openCard([
                    'pcustID' => $customer->pcustID,
                    'custID' => $customer->custID,
                    'mobile' => $customer->mobile
                ]);
            }
        }

        $pcustID = $customer->pcustID;

        //执行登录
        if ($platform == 6) {
            //微信小程序会员表 wx_applet_customer
            $user_info = Redis::get('WX_APPLET_USER_'.$session_id );
            if ( $user_info ) {
                $user_info  = json_decode( $user_info,true );
                $id = $user_info['id'];
                $wx_applet_customer = WxAppletCustomer::find($id);
                if ( $wx_applet_customer ) {
                    $wx_applet_customer->pcustID = $pcustID;
                    $wx_applet_customer->save();
                }
                $user_info['pcustID'] = $pcustID;
                Redis::setex( 'WX_APPLET_USER_' . $session_id, 604800, json_encode( $user_info, true ) );
            }
        }

        return response()->json(['code' => 200, 'message' => 'ok', 'data' => $result['data']]);
    }

}